#include <iostream>
using namespace std;

// 定义单链表结点
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

// 将单链表按基准划分
ListNode* partition(ListNode* head, int x) {
    ListNode *small = new ListNode(0); // 小于x的结点链表
    ListNode *large = new ListNode(0); // 大于等于x的结点链表
    ListNode *p = head, *p1 = small, *p2 = large;
    while (p != NULL) {
        if (p->val < x) {
            p1->next = p;
            p1 = p1->next;
        } else {
            p2->next = p;
            p2 = p2->next;
        }
        p = p->next;
    }
    p2->next = NULL;
    p1->next = large->next;
    return small->next;
}

// 测试
int main() {
    ListNode *head = new ListNode(1);
    head->next = new ListNode(4);    head->next->next = new ListNode(3);
    head->next->next->next = new ListNode(2);
    head->next->next->next->next = new ListNode(5);
    head = partition(head, 3);
    while (head != NULL) {
        cout << head->val << " ";
        head = head->next;
    }
    return 0;
}